<?php
namespace Hilaoyu\ComputeCloudClient;

use AlibabaCloud\SDK\Cbn\V20170912\Cbn;
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\AttachKeyPairResponseBody\results\result;
use AlibabaCloud\SDK\ResourceManager\V20200331\ResourceManager;
use AlibabaCloud\SDK\Vpc\V20160428\Vpc;
use AlibabaCloud\Tea\Model;
use Darabonba\OpenApi\Models\Config;
use Hilaoyu\ComputeCloudClient\Api\AliCbn;
use Hilaoyu\ComputeCloudClient\Interfaces\ComputeCloudClientInterface;
use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\ComputeCloudClient\Api\AliEcs;
use Hilaoyu\ComputeCloudClient\Api\AliResourceManager;
use Hilaoyu\ComputeCloudClient\Api\AliVpc;
use IPTools\Network;

class AliyunApi implements ComputeCloudClientInterface
{
    use ErrorsTrait;

    protected $config;

    static public function make($accessKeyId, $accessKeySecret){
        return new static($accessKeyId, $accessKeySecret);
    }

    public function __construct($accessKeyId, $accessKeySecret){
        $this->config = $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
    }

    protected function endpointConfig($endpoint){
        $config = $this->config;
        $config->endpoint = trim($endpoint);
        return $config;
    }


    public function vpc($regionId=''){
        $regionId = trim($regionId);

        if($regionId){
            $endpoint = 'vpc.'.$regionId.'.aliyuncs.com';
        }else{
            $endpoint = 'vpc.aliyuncs.com';
        }
        $ali_client = new Vpc($this->endpointConfig($endpoint));

        return new AliVpc($ali_client,$this,$regionId);

    }
    public function cbn($regionId=''){
        $ali_client = new Cbn($this->endpointConfig('cbn.aliyuncs.com'));

        return new AliCbn($ali_client,$this,$regionId);

    }

    public function ecs($regionId=''){
        $regionId = trim($regionId);

        if($regionId){
            $endpoint = 'ecs.'.$regionId.'.aliyuncs.com';
        }else{
            $endpoint = 'ecs.aliyuncs.com';
        }
        $ali_client = new Ecs($this->endpointConfig($endpoint));

        return new AliEcs($ali_client,$this,$regionId);

    }

    static public function GetGateWay(string $network) :string{
        try{
            $network = Network::parse($network);
            return (string)$network->getLastIP()->prev(2);
        }catch (\Exception $exception){
            return "";
        }

    }

}
